package com.itlin.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itlin.constant.MessageConstant;
import com.itlin.constant.RedisMessageConstant;
import com.itlin.entity.Result;
import com.itlin.pojo.Member;
import com.itlin.pojo.MemberOrder;
import com.itlin.service.MemberService;
import com.itlin.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 会员登录
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;

    //使用手机号和验证码登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取缓存的验证码
        Jedis jedis = jedisPool.getResource();
        String codeInRedis =
                jedis.get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);
        if(codeInRedis == null || !codeInRedis.equals(validateCode)){
            jedis.close();
            //验证码输入错误
            System.out.println("验证码错误");
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }else{
            //验证码输入正确
            System.out.println("验证码正确");
            //判断当前用户是否为会员
            Member member = memberService.findByTelephone(telephone);
            if(member == null){
                //当前用户不是会员，自动完成注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //登录成功
            //写入Cookie，跟踪用户
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60*60*24*30);//有效期30天
            response.addCookie(cookie);
            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedis.setex(telephone,60*30,json);
            jedis.close();
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }
    }

    @RequestMapping("/loginpassword")
    public Result loginpassword(HttpServletResponse response, @RequestBody Map map){
        String telephone = (String) map.get("telephone");
        String password = (String) map.get("password");
        //从Redis中获取缓存的验证码
        // Jedis jedis = jedisPool.getResource();
        Jedis jedis = new Jedis();
        //判断当前用户是否为会员
        Member member = memberService.findByTelephone(telephone);
        if(member == null){
            //当前用户不是会员，请验证码登录完成注册
            return new Result(false,MessageConstant.ACCOUNT_NULL);
        }
        String md5 = MD5Utils.md5(password);
        if (telephone.equals(member.getPhoneNumber()) && md5.equals(member.getPassword())){
            //登录成功
            //写入Cookie，跟踪用户
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60*60*24*30);//有效期30天
            response.addCookie(cookie);
            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedis.setex(telephone,60*30,json);
            jedis.close();
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }
        return new Result(false,MessageConstant.LOGIN_FAIL);
    }

    //查询用户预约套餐
    @RequestMapping("/findByMemberOrder")
    public Result findByMemberOrder(String phoneNumber){
        Member member = null;
        try {
            member = memberService.findByTelephone(phoneNumber);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MEMBER_FAIL);
        }
        if (member != null){
            int memberId = member.getId();
            List<MemberOrder> memberOrder = memberService.findByMemberOrder(memberId);
            System.out.println("进入查询中===========");
            System.out.println(memberOrder.get(0));
            return new Result(true,MessageConstant.QUERY_MEMBER_SETMEAL_SUCCESS,memberOrder);
        }
        return new Result(true,MessageConstant.QUERY_MEMBER_SETMEAL_FAIL);
    }

    //删除
    @RequestMapping("/deleteById")
    public Result deleteById(Integer id){
        try {
            memberService.deleteMemberOrderById(id);
        }catch (RuntimeException e){
            return new Result(false,e.getMessage());
        }catch (Exception e){
            return new Result(false, MessageConstant.ORDER_CANCEL_FAIL);
        }
        return new Result(true,MessageConstant.ORDER_CANCEL_SUCCESS);
    }
}
